<template>
  <div class="role-container">
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.name" placeholder="请输入角色名称" clearable />
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input v-model="searchForm.code" placeholder="请输入角色编码" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <div class="toolbar">
        <div class="left">
          <el-button type="primary" @click="handleAdd" v-permisssion="['role:add']">
            <el-icon><Plus /></el-icon> 新增
          </el-button>
          <el-button
            type="danger"
            :disabled="!selectedRows.length"
            @click="handleBatchDelete"
            v-permisssion="['role:delete']"
          >
            <el-icon><Delete /></el-icon> 批量删除
          </el-button>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="code" label="角色编码" />
        <el-table-column prop="description" label="角色描述" show-overflow-tooltip />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === '1' ? 'success' : 'danger'">
              {{ scope.row.status === '1' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column fixed="right" label="操作" width="300">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button
                link
                type="primary"
                size="small"
                @click="handleEdit(scope.row)"
                v-permisssion="['role:edit']"
                >编辑</el-button
              >
              <el-button
                link
                type="primary"
                size="small"
                @click="handleAssign(scope.row)"
                v-permisssion="['role:assign']"
                >分配权限</el-button
              >
              <el-button
                link
                :type="scope.row.status === '1' ? 'danger' : 'success'"
                size="small"
                @click="handleToggleStatus(scope.row)"
                v-permisssion="['role:edit']"
              >
                {{ scope.row.status === '1' ? '禁用' : '启用' }}
              </el-button>
              <el-button
                link
                type="danger"
                size="small"
                @click="handleDelete(scope.row)"
                v-permisssion="['role:delete']"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      :title="dialogType === 'add' ? '新增角色' : '编辑角色'"
      width="500px"
      destroy-on-close
    >
      <el-form ref="roleFormRef" :model="roleForm" :rules="roleRules" label-width="80px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="roleForm.code" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="roleForm.sort" :min="0" :max="9999" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="roleForm.status">
            <el-radio :value="'1'">启用</el-radio>
            <el-radio :value="'0'">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            placeholder="请输入角色描述"
            :rows="4"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRoleForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog v-model="permDialogVisible" title="分配权限" width="600px">
      <div v-loading="permLoading">
        <el-tree
          ref="permTreeRef"
          :data="permissionTree"
          show-checkbox
          node-key="id"
          :props="{
            label: 'name',
            children: 'children',
          }"
          default-expand-all
          class="permission-tree"
        ></el-tree>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="permDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPermissions">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { Plus, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = reactive({
  name: '',
  code: '',
  status: '',
})

// 表格数据
const loading = ref(false)
const tableData = ref([
  {
    id: '1',
    name: '超级管理员',
    code: 'SUPER_ADMIN',
    description: '系统超级管理员，拥有所有权限',
    sort: 1,
    status: '1',
    createTime: '2023-01-01 12:00:00',
  },
  {
    id: '2',
    name: '运营人员',
    code: 'OPERATOR',
    description: '系统运营人员，负责内容管理和用户管理',
    sort: 2,
    status: '1',
    createTime: '2023-01-02 10:00:00',
  },
  {
    id: '3',
    name: '客服人员',
    code: 'CUSTOMER_SERVICE',
    description: '客服人员，负责处理用户反馈和问题',
    sort: 3,
    status: '1',
    createTime: '2023-01-03 09:00:00',
  },
  {
    id: '4',
    name: '测试角色',
    code: 'TEST_ROLE',
    description: '测试角色，仅用于系统测试',
    sort: 99,
    status: '0',
    createTime: '2023-01-04 14:00:00',
  },
])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

// 选中行
const selectedRows = ref([])

// 角色表单
const roleDialogVisible = ref(false)
const dialogType = ref('add') // add 或 edit
const roleFormRef = ref(null)
const roleForm = reactive({
  id: '',
  name: '',
  code: '',
  sort: 0,
  status: '1',
  description: '',
})
const roleRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  sort: [{ required: true, message: '请输入排序值', trigger: 'blur' }],
}

// 权限分配相关
const permDialogVisible = ref(false)
const permLoading = ref(false)
const permTreeRef = ref(null)
const currentRoleId = ref('')

// 模拟权限树数据
const permissionTree = [
  {
    id: '1',
    name: '系统管理',
    children: [
      {
        id: '1-1',
        name: '用户管理',
        children: [
          { id: '1-1-1', name: '用户查询' },
          { id: '1-1-2', name: '用户新增' },
          { id: '1-1-3', name: '用户修改' },
          { id: '1-1-4', name: '用户删除' },
        ],
      },
      {
        id: '1-2',
        name: '角色管理',
        children: [
          { id: '1-2-1', name: '角色查询' },
          { id: '1-2-2', name: '角色新增' },
          { id: '1-2-3', name: '角色修改' },
          { id: '1-2-4', name: '角色删除' },
          { id: '1-2-5', name: '分配权限' },
        ],
      },
      {
        id: '1-3',
        name: '菜单管理',
        children: [
          { id: '1-3-1', name: '菜单查询' },
          { id: '1-3-2', name: '菜单新增' },
          { id: '1-3-3', name: '菜单修改' },
          { id: '1-3-4', name: '菜单删除' },
        ],
      },
    ],
  },
  {
    id: '2',
    name: '内容管理',
    children: [
      {
        id: '2-1',
        name: '文章管理',
        children: [
          { id: '2-1-1', name: '文章查询' },
          { id: '2-1-2', name: '文章新增' },
          { id: '2-1-3', name: '文章修改' },
          { id: '2-1-4', name: '文章删除' },
        ],
      },
      {
        id: '2-2',
        name: '标签管理',
        children: [
          { id: '2-2-1', name: '标签查询' },
          { id: '2-2-2', name: '标签新增' },
          { id: '2-2-3', name: '标签修改' },
          { id: '2-2-4', name: '标签删除' },
        ],
      },
    ],
  },
]

// 搜索方法
const handleSearch = () => {
  loading.value = true
  // 实际应该调用API接口，这里模拟一下
  setTimeout(() => {
    loading.value = false
    ElMessage.success('搜索成功')
  }, 500)
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.code = ''
  searchForm.status = ''
  handleSearch()
}

// 选择变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  handleSearch()
}

// 分页当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  handleSearch()
}

// 打开新增对话框
const handleAdd = () => {
  dialogType.value = 'add'
  roleForm.id = ''
  roleForm.name = ''
  roleForm.code = ''
  roleForm.sort = 0
  roleForm.status = '1'
  roleForm.description = ''
  roleDialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = (row) => {
  dialogType.value = 'edit'
  roleForm.id = row.id
  roleForm.name = row.name
  roleForm.code = row.code
  roleForm.sort = row.sort
  roleForm.status = row.status
  roleForm.description = row.description
  roleDialogVisible.value = true
}

// 提交角色表单
const submitRoleForm = async () => {
  if (!roleFormRef.value) return
  try {
    await roleFormRef.value.validate()
    loading.value = true
    // 实际应该调用API接口，这里模拟一下
    setTimeout(() => {
      loading.value = false
      roleDialogVisible.value = false
      ElMessage.success(dialogType.value === 'add' ? '添加成功' : '编辑成功')
      handleSearch()
    }, 500)
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

// 切换状态
const handleToggleStatus = (row) => {
  const action = row.status === '1' ? '禁用' : '启用'
  ElMessageBox.confirm(`确定要${action}角色 ${row.name} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // 切换状态的逻辑
      row.status = row.status === '1' ? '0' : '1'
      ElMessage.success(`${action}成功`)
    })
    .catch(() => {})
}

// 删除角色
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除角色 ${row.name} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // 删除角色的逻辑
      ElMessage.success('删除成功')
      handleSearch()
    })
    .catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }

  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // 批量删除的逻辑
      ElMessage.success('批量删除成功')
      handleSearch()
    })
    .catch(() => {})
}

// 分配权限
const handleAssign = (row) => {
  currentRoleId.value = row.id
  permLoading.value = true
  // 实际应该调用API获取角色已有权限，这里模拟一下
  setTimeout(() => {
    permLoading.value = false
    // 模拟已有权限ID
    const checkedKeys = ['1-1-1', '1-1-2', '1-2-1', '2-1-1']
    permTreeRef.value.setCheckedKeys(checkedKeys)
    permDialogVisible.value = true
  }, 500)
}

// 提交权限设置
const submitPermissions = () => {
  // 将来实现实际API调用时可能需要用到这些节点
  // const checkedNodes = permTreeRef.value.getCheckedNodes()
  // const halfCheckedNodes = permTreeRef.value.getHalfCheckedNodes()
  // const allNodes = [...checkedNodes, ...halfCheckedNodes]
  // 提取权限ID用于保存到后端
  // const permIds = allNodes.map((node) => node.id)

  // 实际应该调用API保存权限设置，这里模拟一下
  permLoading.value = true
  setTimeout(() => {
    permLoading.value = false
    permDialogVisible.value = false
    ElMessage.success('权限设置成功')
  }, 500)
}
</script>

<style scoped>
.role-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.search-card,
.table-card {
  margin-bottom: 0;
  transition: all 0.3s;
  border-radius: var(--el-card-border-radius);
  overflow: hidden;
  box-shadow: var(--box-shadow-base);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.operation-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.permission-tree {
  max-height: 400px;
  overflow-y: auto;
  margin: 0 20px;
  border: 1px solid var(--border-color-lighter);
  border-radius: 4px;
  padding: 10px;
}

/* Element Plus 样式覆盖 */

:deep(.el-card) {
  border: 0px solid #fff !important;
}
</style>
